<!--
 * 严肃声明：
 * 开源版本请务必保留此注释头信息，若删除我方将保留所有法律责任追究！
 * 本系统已申请软件著作权，受国家版权局知识产权以及国家计算机软件著作权保护！
 * 可正常分享和学习源码，不得用于违法犯罪活动，违者必究！
 * Copyright (c) 2020 陈尼克 all rights reserved.
 * 版权所有，侵权必究！
 *
-->

<template>
  <div class="product-detail">
    <s-header :name="'商品详情'"></s-header>
    <div class="detail-content">
      <div class="detail-swipe-wrap">
        <van-swipe class="my-swipe" indicator-color="#1baeae">
          <van-swipe-item v-for="(item, index) in detail.goodsCarouselList" :key="index">
            <img :src="prefix(item)" alt="">
          </van-swipe-item>
        </van-swipe>
      </div>

      <div class="product-info">
        <div class="product-title">
          {{ detail.goodsName }}
        </div>
        <div class="product-desc">免邮费 顺丰快递</div>
        <div class="product-price">
          <span class="selling-price">¥{{ detail.sellingPrice }}</span>
          <span class="original-price" v-if="hasDiscount">
            ¥{{ detail.originalPrice }}
          </span>
          <span class="discount-badge" v-if="hasDiscount">
            {{ discountRate }}折
          </span>
        </div>
      </div>

      <div class="product-specs" v-if="specAttrs.length > 0">
        <div class="spec-item" v-for="attr in specAttrs" :key="attr.id">
          <div class="spec-title">{{ attr.attrName }}：</div>
          <div class="spec-values">
            <span
              v-for="value in attr.values"
              :key="value.id"
              :class="['spec-value', { 'active': isValueSelected(attr.id, value.id) }]"
              @click="selectSpecValue(attr.id, value.id)"
            >
              {{ value.valueName }}
            </span>
          </div>
        </div>

        <!-- 显示已选规格 -->
        <div class="selected-specs" v-if="selectedSpecsList.length > 0">
          <span>已选：</span>
          <span v-for="spec in selectedSpecsList" :key="spec.attrId" class="selected-item">
            {{ spec.attrName }}: {{ spec.valueName }}
          </span>
        </div>
      </div>

      <div class="product-intro">
        <ul>
          <li>商品简介</li>
          <!-- <li>参数</li>
          <li>安装服务</li>
          <li>常见问题</li> -->
        </ul>
        <div class="product-content" v-html="detail.goodsDetailContent"></div>
      </div>
    </div>

    <!-- 底部操作栏 -->
    <van-goods-action>
      <van-goods-action-icon icon="cart-o" :info="!count ? '' : count" @click="goToCart" text="购物车"/>
      <van-goods-action-button type="warning" @click="addCart" text="加入购物车" />
      <van-goods-action-button type="danger" @click="goToCartDirect" text="立即购买" />
    </van-goods-action>

    <!-- 规格选择弹窗 -->
    <van-popup v-model="showSpecPopup" position="bottom" round>
      <div class="spec-popup">
        <div class="popup-header">
          <div class="product-info">
            <div class="product-details">
              <div class="price-section">
                <span class="selling-price">¥{{ detail.sellingPrice }}</span>
                <span class="original-price" v-if="hasDiscount">
                  ¥{{ detail.originalPrice }}
                </span>
                <span class="discount-badge" v-if="hasDiscount">
                  {{ discountRate }}折
                </span>
              </div>
              <div class="selected">已选：{{ getSelectedSpecText() }}</div>
            </div>
          </div>
        </div>

        <div class="spec-options">
          <div class="spec-option" v-for="attr in specAttrs" :key="attr.id">
            <div class="option-title">{{ attr.attrName }}</div>
            <div class="option-values">
              <span
                v-for="value in attr.values"
                :key="value.id"
                :class="['option-value', {
                  'active': isValueSelected(attr.id, value.id)
                }]"
                @click="selectPopupSpecValue(attr.id, value.id)"
              >
                {{ value.valueName }}
              </span>
            </div>
          </div>
        </div>

        <div class="quantity-selector">
          <div class="quantity-title">购买数量</div>
          <van-stepper v-model="quantity" integer min="1" />
        </div>

        <div class="popup-actions">
          <van-button type="warning" size="large" @click="confirmAddCart">加入购物车</van-button>
          <van-button type="danger" size="large" @click="confirmBuyNow">立即购买</van-button>
        </div>
      </div>
    </van-popup>
  </div>
</template>

<script>
import { getDetail } from '../service/good'
import { getGoodsSpecs } from '../service/goodsSpec'
import { addCart } from '../service/cart'
import sHeader from '@/components/SimpleHeader'
import { Toast, Popup, Button, Stepper } from 'vant'

export default {
  data() {
    return {
      detail: {
        goodsCarouselList: [],
        originalPrice: 0,
        sellingPrice: 0,
        goodsName: '',
        goodsId: null,
        goodsDetailContent: ''
      },
      specAttrs: [], // 规格属性列表
      selectedSpecs: {}, // 选中的规格 {attrId: valueId}
      showSpecPopup: false, // 是否显示规格弹窗
      quantity: 1, // 购买数量
      currentImage: '' // 当前显示的图片
    }
  },
  components: {
    sHeader,
    [Popup.name]: Popup,
    [Button.name]: Button,
    [Stepper.name]: Stepper
  },
  computed: {
    count() {
      return this.$store.state.cartCount
    },

    // 计算已选规格列表（用于显示）
    selectedSpecsList() {
      const specs = []
      this.specAttrs.forEach(attr => {
        const valueId = this.selectedSpecs[attr.id]
        if (valueId) {
          const value = attr.values.find(v => v.id === valueId)
          if (value) {
            specs.push({
              attrId: attr.id,
              attrName: attr.attrName,
              valueId: value.id,
              valueName: value.valueName
            })
          }
        }
      })
      return specs
    },

    // 计算是否有折扣
    hasDiscount() {
      return this.detail.originalPrice > this.detail.sellingPrice
    },

    // 计算折扣率
    discountRate() {
      if (this.detail.originalPrice > 0 && this.detail.originalPrice > this.detail.sellingPrice) {
        const discount = (this.detail.sellingPrice / this.detail.originalPrice * 10).toFixed(1)
        return discount
      }
      return 10
    }
  },
  async mounted() {
    const { id } = this.$route.params
    await this.loadProductDetail(id)
    await this.loadProductSpecs(id)
  },
  methods: {
    prefix(url) {
      if (url && url.startsWith('http')) {
        return url
      } else {
        return url ? 'https://172.26.200.76:28019' + url : ''
      }
    },

    async loadProductDetail(id) {
      try {
        const { data } = await getDetail(id)
        this.detail = data

        // 如果没有原价数据，默认设置原价等于售价
        if (!this.detail.originalPrice || this.detail.originalPrice === 0) {
          this.detail.originalPrice = this.detail.sellingPrice
        }
      } catch (error) {
        Toast.fail('加载商品详情失败')
        console.error('加载商品详情失败:', error)
      }
    },

    async loadProductSpecs(goodsId) {
      try {
        // 调用接口获取商品规格信息
        const { data } = await getGoodsSpecs(goodsId)
        this.specAttrs = data

        // 初始化选中状态
        this.selectedSpecs = {}
        this.specAttrs.forEach(attr => {
          if (attr.values && attr.values.length > 0) {
            this.selectedSpecs[attr.id] = null // 初始化为未选择
          }
        })
      } catch (error) {
        this.specAttrs = []
        console.error('加载商品规格失败:', error)
      }
    },

    // 选择规格值
    selectSpecValue(attrId, valueId) {
      if (this.selectedSpecs[attrId] === valueId) {
        this.selectedSpecs[attrId] = null
      } else {
        this.selectedSpecs[attrId] = valueId
      }
      this.$forceUpdate()
    },

    // 弹窗内选择规格值
    selectPopupSpecValue(attrId, valueId) {
      this.selectSpecValue(attrId, valueId)
    },

    // 检查规格值是否被选中
    isValueSelected(attrId, valueId) {
      return this.selectedSpecs[attrId] === valueId
    },

    // 获取已选规格文本
    getSelectedSpecText() {
      const selected = []
      this.specAttrs.forEach(attr => {
        const valueId = this.selectedSpecs[attr.id]
        if (valueId) {
          const value = attr.values.find(v => v.id === valueId)
          if (value) {
            selected.push(`${attr.attrName}: ${value.valueName}`)
          }
        }
      })
      return selected.length > 0 ? selected.join('; ') : '请选择规格'
    },

    // 显示规格选择弹窗
    showSpecSelector() {
      this.showSpecPopup = true
      this.quantity = 1
    },

    // 加入购物车
    async addCart() {
      const unselectedAttrs = this.specAttrs.filter(attr =>
        !this.selectedSpecs[attr.id] && attr.values.length > 0
      )

      if (unselectedAttrs.length > 0) {
        this.showSpecSelector()
        return
      }

      await this.confirmAddCart()
    },

    // 确认加入购物车
    async confirmAddCart() {
      try {
        // 检查是否选择了所有必要的规格
        const unselectedAttrs = this.specAttrs.filter(attr =>
          !this.selectedSpecs[attr.id] && attr.values.length > 0
        )

        if (unselectedAttrs.length > 0) {
          Toast.fail('请选择完整规格')
          return
        }

        const params = {
          goodsCount: this.quantity,
          goodsId: this.detail.goodsId
        }

        // 如果有选中的规格，添加到参数中
        const specData = this.getSelectedSpecData()
        if (Object.keys(specData).length > 0) {
          params.specData = JSON.stringify(specData)
        }

        const { resultCode } = await addCart(params)

        if (resultCode == 200) {
          Toast.success('添加成功')
          this.showSpecPopup = false
          this.$store.dispatch('updateCart')
        } else {
          Toast.fail('添加失败')
        }
      } catch (error) {
        Toast.fail('添加失败')
        console.error('添加购物车失败:', error)
      }
    },

    // 立即购买
    goToCartDirect() {
      const unselectedAttrs = this.specAttrs.filter(attr =>
        !this.selectedSpecs[attr.id] && attr.values.length > 0
      )

      if (unselectedAttrs.length > 0) {
        this.showSpecSelector()
        return
      }

      this.confirmBuyNow()
    },

    // 确认立即购买
    async confirmBuyNow() {
      try {
        // 检查是否选择了所有必要的规格
        const unselectedAttrs = this.specAttrs.filter(attr =>
          !this.selectedSpecs[attr.id] && attr.values.length > 0
        )

        if (unselectedAttrs.length > 0) {
          Toast.fail('请选择完整规格')
          return
        }

        const params = {
          goodsCount: this.quantity,
          goodsId: this.detail.goodsId
        }

        // 如果有选中的规格，添加到参数中
        const specData = this.getSelectedSpecData()
        if (Object.keys(specData).length > 0) {
          params.specData = JSON.stringify(specData)
        }

        const { resultCode } = await addCart(params)

        if (resultCode == 200) {
          Toast.success('添加成功')
          this.showSpecPopup = false
          this.$store.dispatch('updateCart')
          this.$router.push({ path: '/cart' })
        } else {
          Toast.fail('添加失败')
        }
      } catch (error) {
        Toast.fail('添加失败')
        console.error('立即购买失败:', error)
      }
    },

    goToCart() {
      this.$router.push({ path: '/cart' })
    },

    // 获取选中的规格数据
    getSelectedSpecData() {
      const specData = {}
      this.specAttrs.forEach(attr => {
        const valueId = this.selectedSpecs[attr.id]
        if (valueId) {
          const value = attr.values.find(v => v.id === valueId)
          if (value) {
            specData[attr.attrKey] = {
              attrId: attr.id,
              attrName: attr.attrName,
              valueId: value.id,
              valueName: value.valueName
            }
          }
        }
      })
      return specData
    }
  }
}
</script>

<style lang="less" scoped>
@import '../common/style/mixin';

.product-detail {
  .detail-content {
    margin-top: 44px;
    padding-bottom: 50px;

    .detail-swipe-wrap {
      .my-swipe .van-swipe-item {
        img {
          width: 100%;
        }
      }
    }

    .product-info {
      padding: 15px;
      background: white;
      margin-bottom: 10px;

      .product-title {
        font-size: 18px;
        color: #333;
        line-height: 1.4;
        font-weight: 500;
        margin-bottom: 8px;
      }

      .product-desc {
        font-size: 14px;
        color: #999;
        padding: 8px 0;
        margin-bottom: 10px;
      }

      .product-price {
        display: flex;
        align-items: center;
        gap: 10px;

        .selling-price {
          color: #F63515;
          font-size: 22px;
          font-weight: bold;
        }

        .original-price {
          color: #999;
          font-size: 16px;
          text-decoration: line-through;
        }

        .discount-badge {
          background: linear-gradient(135deg, #ff6b6b, #ff8e8e);
          color: white;
          padding: 2px 8px;
          border-radius: 12px;
          font-size: 12px;
          font-weight: bold;
        }
      }
    }

    .product-specs {
      background: white;
      padding: 15px;
      margin-bottom: 10px;

      .spec-item {
        margin-bottom: 15px;

        .spec-title {
          font-size: 14px;
          color: #333;
          margin-bottom: 10px;
          font-weight: 500;
        }

        .spec-values {
          display: flex;
          flex-wrap: wrap;
          gap: 10px;

          .spec-value {
            padding: 8px 15px;
            border: 1px solid #e5e5e5;
            border-radius: 4px;
            font-size: 12px;
            cursor: pointer;
            transition: all 0.3s ease;
            background: #f8f8f8;

            &.active {
              border-color: @primary;
              color: @primary;
              background: rgba(@primary, 0.1);
              font-weight: 500;
            }

            &:hover {
              border-color: #ccc;
            }
          }
        }
      }

      .selected-specs {
        padding-top: 10px;
        border-top: 1px solid #f5f5f5;
        font-size: 13px;
        color: #666;

        .selected-item {
          margin-right: 10px;
          background: #f8f8f8;
          padding: 2px 6px;
          border-radius: 3px;

          &:not(:last-child):after {
            content: ';';
            margin-left: 5px;
          }
        }
      }
    }

    .product-intro {
      width: 100%;
      background: white;

      ul {
        .fj();
        width: 100%;
        margin: 0;
        border-bottom: 1px solid #f5f5f5;

        li {
          flex: 1;
          padding: 15px 0;
          text-align: center;
          font-size: 14px;
          border-right: 1px solid #f5f5f5;
          box-sizing: border-box;

          &:last-child {
            border-right: none;
          }
        }
      }

      .product-content {
        padding: 0 20px;
        width: 100%;
        box-sizing: border-box;

        // 使用深度选择器修复图片样式
        ::v-deep img {
          max-width: 100% !important;
          height: auto !important;
          display: block;
          margin: 0 auto;
        }

        ::v-deep table {
          max-width: 100% !important;
          width: auto !important;
          overflow-x: auto;
          display: block;
        }

        ::v-deep * {
          max-width: 100% !important;
          box-sizing: border-box;
        }
      }
    }
  }

  // 规格弹窗样式
  .spec-popup {
    padding: 20px;
    max-height: 80vh;
    overflow-y: auto;

    .popup-header {
      .product-info {
        display: flex;
        gap: 15px;
        padding-bottom: 15px;
        border-bottom: 1px solid #f5f5f5;

        .product-details {
          flex: 1;

          .price-section {
            display: flex;
            align-items: center;
            gap: 8px;
            margin-bottom: 5px;

            .selling-price {
              color: #F63515;
              font-size: 18px;
              font-weight: bold;
            }

            .original-price {
              color: #999;
              font-size: 14px;
              text-decoration: line-through;
            }

            .discount-badge {
              background: linear-gradient(135deg, #ff6b6b, #ff8e8e);
              color: white;
              padding: 2px 6px;
              border-radius: 10px;
              font-size: 10px;
              font-weight: bold;
            }
          }

          .selected {
            font-size: 12px;
            color: #666;
          }
        }
      }
    }

    .spec-options {
      .spec-option {
        padding: 15px 0;
        border-bottom: 1px solid #f5f5f5;

        &:last-child {
          border-bottom: none;
        }

        .option-title {
          font-size: 14px;
          color: #333;
          margin-bottom: 10px;
          font-weight: 500;
        }

        .option-values {
          display: flex;
          flex-wrap: wrap;
          gap: 10px;

          .option-value {
            padding: 8px 15px;
            border: 1px solid #e5e5e5;
            border-radius: 4px;
            font-size: 12px;
            cursor: pointer;
            transition: all 0.3s ease;
            background: #f8f8f8;

            &.active {
              border-color: @primary;
              color: @primary;
              background: rgba(@primary, 0.1);
              font-weight: 500;
            }

            &:hover {
              border-color: #ccc;
            }
          }
        }
      }
    }

    .quantity-selector {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 15px 0;
      border-bottom: 1px solid #f5f5f5;

      .quantity-title {
        font-size: 14px;
        color: #333;
        font-weight: 500;
      }
    }

    .popup-actions {
      display: flex;
      gap: 10px;
      padding-top: 15px;

      .van-button {
        flex: 1;
        height: 44px;
        border-radius: 22px;
        font-size: 16px;
        font-weight: 500;
      }
    }
  }

  .van-goods-action-button--warning {
    background: linear-gradient(to right, #6bd8d8, @primary)
  }

  .van-goods-action-button--danger {
    background: linear-gradient(to right, #0dc3c3, #098888)
  }
}
</style>
